package com.zhz.mall.sercurity.config;

import com.zhz.mall.common.util.jwt.JwtTokenUtil;
import com.zhz.mall.sercurity.component.JwtAuthenticationFilter;
import com.zhz.mall.sercurity.component.RestfulAccessDeniedHandler;
import com.zhz.mall.sercurity.component.RestfulAuthenticationEntryPoint;
import com.zhz.mall.sercurity.component.dynamicSecurity.DynamicAccessDecisionManager;
import com.zhz.mall.sercurity.component.dynamicSecurity.DynamicSecurityFilter;
import com.zhz.mall.sercurity.component.dynamicSecurity.DynamicSecurityMetadataSource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * @author zhouhengzhe
 * @date 2023/2/5
 */
@Component
@Configuration
public class SecurityConfig {
    /**
     * jwt工具类
     *
     * @return
     */
    @Bean
    public JwtTokenUtil jwtTokenUtil() {
        return new JwtTokenUtil();
    }

    @Bean
    public JwtAuthenticationFilter jwtAuthenticationFilter() {
        return new JwtAuthenticationFilter();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public RestfulAccessDeniedHandler restfulAccessDeniedHandler() {
        return new RestfulAccessDeniedHandler();
    }


    @Bean
    public RestfulAuthenticationEntryPoint restfulAuthenticationEntryPoint() {
        return new RestfulAuthenticationEntryPoint();
    }

    /**
     * 作用：根据当前请求url获取对应角色
     *
     * @return
     */
    @ConditionalOnBean(name = "dynamicSecurityService")
    @Bean
    public DynamicAccessDecisionManager dynamicAccessDecisionManager() {
        return new DynamicAccessDecisionManager();
    }

    /**
     * 作用：在FilterSecurityInterceptor前面的自定义过滤器
     *
     * @return
     */
    @ConditionalOnBean(name = "dynamicSecurityService")
    @Bean
    public DynamicSecurityFilter dynamicSecurityFilter() {
        return new DynamicSecurityFilter();
    }

    /**
     * 作用：鉴权
     *
     * @return
     */
    @ConditionalOnBean(name = "dynamicSecurityService")
    @Bean
    public DynamicSecurityMetadataSource dynamicSecurityMetadataSource() {
        return new DynamicSecurityMetadataSource();
    }

}
